<script setup lang="ts">
import { ElLoading } from 'element-plus'

import config from '@/config'
import useUserStore from '@/stores/modules/user'
import { objectToQuery } from '@/utils/util'

const props = defineProps({
  api: {
    type: String,
    default: 'project.room/export'
  },
  name: {
    type: String,
    default: '导出'
  },
  suffix: {
    type: String,
    default: 'xlsx'
  },
  params: {
    type: Object,
    default: () => ({})
  },
  before: {
    type: Function
  },
  btnName: {
    type: String,
    default: '导出'
  }
})

const handleClick = async () => {
  if (props.before && typeof props.before === 'function') {
    if (!props.before()) return
  }
  const loadingInstance = ElLoading.service()
  try {
    const a = document.createElement('a')
    const userStore = useUserStore()
    const url = `${config.baseUrl}adminapi/${props.api}?token=${userStore.token}&${objectToQuery(
      props.params
    )}`
    a.setAttribute('href', url)
    a.setAttribute('download', `${props.name}${new Date().getTime()}.${props.suffix}`)
    a.click()
    loadingInstance.close()
  } catch (e) {
    loadingInstance.close()
  }
}
</script>

<template>
  <el-button @click="handleClick">{{ btnName }}</el-button>
</template>

<style scoped lang="scss"></style>
